import React, { useEffect, useRef } from 'react';
import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'; // 轨道控制
import { GUI } from 'lil-gui';
export default function index() {
  const mountRef = useRef(null);
  const gui = new GUI();
  useEffect(() => {
    // 场景
    const scene = new THREE.Scene();
    // 相机
    const camera = new THREE.PerspectiveCamera(75);
    camera.position.z = 5;
    camera.position.x = 1;
    camera.position.y = 1;
    scene.add(camera);
    // 网格体
    const boxGeometry = new THREE.BoxGeometry(1, 1, 1);
    const boxMeterial = new THREE.MeshBasicMaterial({ color: 0xff0000 });
    const boxMesh = new THREE.Mesh(boxGeometry, boxMeterial);
    scene.add(boxMesh);

    // 渲染器
    const renderer = new THREE.WebGLRenderer();
    renderer.setSize(window.innerWidth, window.innerHeight);
    mountRef.current.appendChild(renderer.domElement); // 将渲染器的DOM元素添加到React组件
    renderer.render(scene, camera);

    // 轨道控制
    const controls = new OrbitControls(camera, renderer.domElement);

    // 动画
    const animate = () => {
      controls.update();
      renderer.render(scene, camera);
      window.requestAnimationFrame(animate); // 会在下一帧调用此函数
    };
    animate();

    // 添加gui调试面板
    const guiControls = {
      positionX: boxMesh.position.x,
      positionY: boxMesh.position.y,
      positionZ: boxMesh.position.z,
    };

    gui.add(guiControls, 'positionX', -5, 5).onChange((value) => {
      boxMesh.position.x = value;
    });
    gui.add(guiControls, 'positionY', -5, 5).onChange((value) => {
      boxMesh.position.y = value;
    });
    gui.add(guiControls, 'positionZ', -5, 5).onChange((value) => {
      boxMesh.position.z = value;
    });
  }, []);

  return (
    <div
      ref={mountRef}
      style={{ width: '100%', height: '100vh' }}
    />
  );
}
